# tool macros
CC       ?= gcc
CXX      ?= g++
CFLAGS   := -g -Wall -lpthread
CXXFLAGS :=
DBGFLAGS := -g -lpthread
COBJFLAGS := $(CFLAGS) -c
TARGET_NAME := jkk2206-fw

# path macros
SRC_PATH := src driver
BIN_PATH := compile/bin
OBJ_PATH := compile/obj
DBG_PATH := compile/debug

# compile macros
ifeq ($(OS),Windows_NT)
	TARGET_NAME := $(addsuffix .exe,$(TARGET_NAME))
endif
TARGET := $(BIN_PATH)/$(TARGET_NAME)
TARGET_DEBUG := $(DBG_PATH)/$(TARGET_NAME)

# src files & obj files
SRCS := $(foreach dir, $(SRC_PATH), $(wildcard $(dir)/*.c))
OBJ := $(addprefix $(OBJ_PATH)/, $(addsuffix .o, $(notdir $(basename $(SRCS)))))
OBJ_DEBUG := $(addprefix $(DBG_PATH)/, $(addsuffix .o, $(notdir $(basename $(SRCS)))))

# clean files list
DISTCLEAN_LIST := $(OBJ) \
                  $(OBJ_DEBUG)
CLEAN_LIST := $(TARGET) \
			  $(TARGET_DEBUG) \
			  $(DISTCLEAN_LIST)

# vpath for source files
vpath %.c $(SRC_PATH)

# default rule
default: makedir all ${TARGET_NAME}

${TARGET_NAME}:
	@ln -s compile/bin/$@

# non-phony targets
$(TARGET): $(OBJ)
	$(CC) -o $@ $(OBJ) $(CFLAGS)

$(OBJ_PATH)/%.o: %.c
	$(CC) $(COBJFLAGS) -o $@ $<

$(DBG_PATH)/%.o: %.c
	$(CC) $(COBJFLAGS) $(DBGFLAGS) -o $@ $<

$(TARGET_DEBUG): $(OBJ_DEBUG)
	$(CC) $(CFLAGS) $(DBGFLAGS) $(OBJ_DEBUG) -o $@

# phony rules
.PHONY: makedir
makedir:
	@mkdir -p $(BIN_PATH) $(OBJ_PATH) $(DBG_PATH)

.PHONY: all
all: $(TARGET)

.PHONY: install
install:
	@echo "install /usr/local/bin/$(TARGET_NAME)"
	@cp $(TARGET) /usr/local/bin/$(TARGET_NAME)

.PHONY: debug
debug: $(TARGET_DEBUG)

.PHONY: clean
clean:
	@echo CLEAN $(CLEAN_LIST)
	@rm -f $(CLEAN_LIST)

.PHONY: distclean
distclean:
	@echo CLEAN $(DISTCLEAN_LIST)
	@rm -f $(DISTCLEAN_LIST)